package com.poker.duiued;

import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

import com.poker.iuious.yhyhjs.jklimj.User;
import com.poker.jkiuus.R;
import com.poker.jkiuus.uyrfgd.AppManager;
import com.poker.jkiuus.uyrfgd.DatabaseHelper;

import java.util.List;

public class UsageRecordsActivity extends AppCompatActivity {
    private ListView dateListView;
    private DatabaseHelper databaseHelper;
    private ArrayAdapter<String> dateAdapter;
    private List<String> dates;
    private int userId;
    private String userName;
    private Button btn_back;
    private User user = new User();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usagerecords);
        AppManager.addActivity(this);

        databaseHelper = new DatabaseHelper(this);
        dateListView = findViewById(R.id.date_list_view);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(v -> UsageRecordsActivity.super.onBackPressed());
        userId = getCurrentUserId();

        loadDates();
        setupDateListView();
    }

    private void loadDates() {
        dates = databaseHelper.getDistinctDates(userId);
    }

    private void setupDateListView() {
        dateAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dates);
        dateListView.setAdapter(dateAdapter);
        dateListView.setOnItemClickListener((parent, view, position, id) -> {
            String selectedDate = dates.get(position);
            showQueriesForDate(selectedDate);
        });
    }

    private void showQueriesForDate(String date) {
        List<String> queries = databaseHelper.getQueriesByDate(userId, date);
        AlertDialog.Builder builder = new AlertDialog.Builder(UsageRecordsActivity.this);
        builder.setTitle("Questions on " + date)
                .setItems(queries.toArray(new String[0]), null)
                .setPositiveButton("OK", null).setCancelable(false)
                .show();
    }

    private int getCurrentUserId() {
        userName = getIntent().getStringExtra("USER_NAME");
        user = databaseHelper.queryUserByNameOrEmail(userName);
        return user.getId();
    }
}
